const Table = require('cli-table2')
const colors = require('colors')

module.exports.formatResult = function(result, pathMap, targetConfig) {
  const summaries = []

  summaries.push(getBaseSummary(result, targetConfig))

  summaries.push(getPercent(pathMap))

  if (result.errors) {
    summaries.push(getErrors(result))
  }

  return summaries.join('\n')
}

function getBaseSummary(result, targetConfig) {
  const summary1 = new Table({
    head: [
      'Total Requests',
      'RPS',
      'Clients',
      'totalTimeSeconds',
      'Mean Latency(ms)',
      'Max Latency(ms)',
      'Total Errors'
    ],
    style: { head: ['green'] }
  })
  summary1.push([
    result.totalRequests,
    result.rps,
    targetConfig.clientCount,
    result.totalTimeSeconds,
    result.meanLatencyMs,
    result.maxLatencyMs,
    result.totalErrors
  ])
  return summary1
}

function getPercent(pathMap) {
  const summary2 = new Table({
    head: ['Path', 'Count'],
    style: { head: ['green'] }
  })

  const percentKeys = Object.keys(pathMap)

  summary2.push(...percentKeys.map(path => [path, pathMap[path]]))
  return summary2
}

function getErrors(result) {
  const summary3 = new Table({ style: { head: [], border: [] } })
  const errorKeys = Object.keys(result.errors)
  summary3.push([{ colSpan: errorKeys.length, hAlign: 'center', content: colors.red('Errors') }])
  summary3.push(['code', ...errorKeys])
  summary3.push(['count', ...errorKeys.map(k => result.errors[k])])
  return summary3
}
